package com.example.nettyudp.service.impl;

import com.example.nettyudp.server.NettyBean;
import com.example.nettyudp.service.NettyService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;

/**
 * @author FDJ,
 * @date 2020/5/26,
 * @time 13:59
 */
@Slf4j
@Service
public class NettyServiceImpl implements NettyService {

    @Autowired
    NettyBean nettyBean;

    @Value("${netty.to.ip}")
    private String ip;

    @Value("${netty.to.port}")
    private int port;

    @Override
    public String sendMessage(String str) {
        try {
            // 由于数据报的数据是以字符数组传的形式存储的，所以传转数据
            byte[] bytes = str.getBytes("UTF-8");
            InetSocketAddress address = new InetSocketAddress(ip, port);
            ByteBuf byteBuf = Unpooled.buffer(10);
            byteBuf.writeBytes(bytes);
            DatagramPacket datagramPacket = new DatagramPacket(byteBuf, address);
            nettyBean.getChannel().forEach((k, v) -> {
                System.out.println(k);
                v.writeAndFlush(datagramPacket);
            });
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return "发送失败";
        }
        return "发送成功";
    }
}
